package com.example.demo.ShiroConfig;

import com.example.demo.Services.UserService;
import com.example.demo.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * ClassName:myRealm
 * Package:com.example.demo.ShiroConfig
 * Description:
 * 自定义myrealm
 * @date:2019/12/13 9:07
 * @author:
 */
public class myRealm extends AuthorizingRealm {

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权拦截");

        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //获取当前登录用户(是在认证时候传过来的)
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //就当目前的权限是从数据库取的
        info.addStringPermission("Admins");

        return info;
    }





    @Autowired
    private UserService userService;


    /**
     * 执行认证逻辑
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
//       String name = "jonou";
//       String password = "123456";
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User user = userService.findByname(token.getUsername());
        System.out.println("userInfo"+user);
        if(user==null){
            return null;
        }

        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
